package com.cn.test.ui.example;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cn.test.R;
import com.cn.test.base.BaseActivity;
import com.cn.test.model.ScanBean;
import com.cn.test.model.response.UserInfoBean;
import com.cn.test.mvp.presenter.LoginUserPresenter;
import com.cn.test.mvp.presenter.view.LoginUserView;
import com.cn.test.util.LogUtil;
import com.cn.test.util.ToastUtil;
import com.google.android.material.appbar.AppBarLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Created by chengaofu on 2016/12/16 0016.
 */
public class MyWebView extends BaseActivity<LoginUserView, LoginUserPresenter> implements LoginUserView {

    @BindView(R.id.pb_progress)
    ProgressBar pb_progress;
    String url = "";
    String title = "";
    //是否来自公告  来自公告显示的是 HTML代码
    boolean isFromNotic;

    WebView webView;

    @Override
    protected int getNormalLayoutId() {
        return R.layout.webview_layout;
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.webview_layout;
    }

    @Override
    protected LoginUserPresenter createPresenter() {
        return new LoginUserPresenter(this, this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Debug", "到达onre素么中");
    }

    @Override
    protected void initViewsAndEvents() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        webView = (WebView) findViewById(R.id.webView);
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        isFromNotic = getIntent().getBooleanExtra("isFromNotic", false);
        init(url);
        initPermission();
    }

    /**
     * 添加或是更改 成功刷新数据
     *
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(ScanBean messageEvent) {
        callJs(messageEvent.text);
    }

    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(
                Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    onStart();
                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(MyWebView.this, "请先同意权限", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void init(String url) {
        //支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webView.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        webView.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        webView.getSettings().setLayoutAlgorithm
                (WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setSupportZoom(true);

        webView.getSettings().setBlockNetworkImage(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(
                    WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setWebChromeClient(new WebChromeClient() {//监听网页加载
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                try {
                    if (pb_progress == null) {
                        return;
                    }
                    if (newProgress == 100) {
                        // 网页加载完成
                        pb_progress.setVisibility(View.GONE);
                    } else {
                        // 加载中
                        pb_progress.setProgress(newProgress);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                //动态获取链接  名字
//                tvTitle.setText(title);
            }

            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {
                super.onReceivedIcon(view, icon);
            }
        });


        //如果不设置WebViewClient，请求会跳转系统浏览器
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242

                if (url.toString().contains("sina.cn")) {
                    view.loadUrl("http://ask.csdn.net/questions/178242");
                    return true;
                }

                return false;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (request.getUrl().toString().contains("sina.cn")) {
                        view.loadUrl("http://ask.csdn.net/questions/178242");
                        return true;
                    }
                }

                return false;
            }

        });
//         url="<p><img alt=\"image.png\" src=\"http://cdn.zyfjsm.com/undefined/20200611/52e55342b423c68919714b90a675613d.png?x-oss-process=style/wenjianyase\" width=\"600\" height=\"578\"><br></p>";
//        if (isFromNotic){
//            webView.loadData(getHtmlData(url), "text/html;charset=utf-8","utf-8");
//        }else {
//        loadData("http://s10txl.shop.touxialan.com/");
        loadData("https://wms.heychic.net/Product/scanCode");
//        }
        webView.addJavascriptInterface(this, "Android");
    }

   String scanCodeMsg="";
    @JavascriptInterface
    public void scanCode(String msg) {
        scanCodeMsg=msg;
//        LogUtil.d("Debug","点击事件---"+msg);
        startActivity(new Intent(this,ScanActivity.class));
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void callJs(String scan_result)
    {
        webView.post(new Runnable() {
            @Override
            public void run() {
                JSONObject jsonMessage = null;
                try {
                    if (TextUtils.isEmpty(scanCodeMsg)){
                        return;
                    }
                    jsonMessage = new JSONObject(scanCodeMsg);
                    String escapedMessage = jsonMessage.toString().replace("'", "\\'");
                    webView.loadUrl("javascript:" + "scanCodeNotify('" + scan_result + "','" + escapedMessage + "');");
                    scanCodeMsg="";
                    LogUtil.d("Debug","daodajic");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void loadData(String mUrl) {
        if (mUrl == null) return;
        if (mUrl.endsWith(".jpg") || mUrl.endsWith(".png")) { //加载图片
            String data = "<HTML><Div align=\"center\"  " +
                    "margin=\"0px\"><IMG  width='100%' height='auto' src=\"" + mUrl + "\" margin=\"0px\"/></Div>";
            webView.loadDataWithBaseURL("", data, "text/html", "utf-8", null);
        } else {
            webView.loadUrl(mUrl); //加载一般网页
        }
    }

    /**
     * 记载html 代码文案
     *
     * @param bodyHTML
     * @return
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>html{padding:15px;} body{word-wrap:break-word;font-size:13px;padding:0px;margin:0px} p{padding:0px;margin:0px;font-size:13px;color:#222222;line-height:1.3;} img{padding:0px,margin:0px;max-width:100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void requestFailed(String message) {

    }

    @Override
    public void onLogin(UserInfoBean resultBean) {

    }
}
